import { useState } from "react";
import { connect, Link, history } from 'umi';
import { Tabs, Input, Skeleton, PageHeader, Descriptions, message, Tooltip, Modal } from 'antd';
import { ClockCircleOutlined } from '@ant-design/icons'
import styles from './style.less';
import { useEffect } from "react";
import { QAStatus } from '../../ProjectQA/QaPage'
import RichText, { RichTextEdit } from '@/components/RichText'
import EditAble from '@/components/EditAble';
import ArrayUtils from '@/utils/ArrayUtils';
import { PROJECT_QA_STATUS } from '@/consts/project'
import { checkRangeDateNotNull, formetDate } from '@/utils/dateUtils'
import UserBrief from '@/components/UserBrief';
import QaCaseList from '../QaCaseList';
import QaModule from './QaModule'
import QaCasePlanList from "../QaCasePlanList";
import { getDetail, update, deleteQa, updateIsArchived } from '@/services/project/qa'
import TextButton from '@/components/TextButton'
import ProjectProdSelect from '@/pages/projects/components/ProjectProduct/ProjectProdSelect'
import ProjectDevSelect from '@/pages/projects/components/ProjectDev/ProjectDevSelect'
import TaskPage from '@/pages/projects/components/ProjectTask/TaskPage'
import ProjectComment from '@/pages/projects/components/ProjectComment'
import ProjectItemLog from '@/pages/projects/components/ProjectItemLog'
import TaskGantt from '@/pages/projects/components/ProjectTask/TaskGantt'
import ActionDropdown from '@/components/ActionDropdown';

const { Search } = Input;
const { TabPane } = Tabs;



const QADetail = (props) => {

    const {
        projectId,
        qaId,
        dispatch,
        routeTabKey,
        projectPermission,
    } = props

    const [tabKey, setTabKey] = useState()
    const [isDetailTextEditFlag, setIsDetailTextEditFlag] = useState();
    const [isProdEditFlag, setIsProdEditFlag] = useState(false);
    const [isDevEditFlag, setIsDevEditFlag] = useState(false)
    const [projectLogUpdate, setProjectLogUpdate] = useState(0)
    const [isModuleEditFlag, setIsModuleEditFlag] = useState(false)
    const [qaDetail, setQaDetail] = useState({})
    const [permission, setPermission] = useState({})

    useEffect(() => {
        getDetail(projectId, qaId).then(({ data }) => {
            setQaDetail(data)
        })
    }, [])

    useEffect(() => {
        setPermission({
            ...projectPermission?.qa
        })
    }, [projectPermission])

    useEffect(() => {
        if (routeTabKey) {
            setTabKey(routeTabKey)
        }
    }, [routeTabKey])

    if (!qaDetail || qaDetail.id !== qaId) {
        return <div className={styles.detailContainer}><Skeleton></Skeleton></div>
    }

    const onChangeTabSwitch = (tabKey) => {
        if (tabKey === "log") {
            setProjectLogUpdate(projectLogUpdate + 1)
        }
        setTabKey(tabKey)
        history.replace(`/projects/${projectId}/qa/${qaId}/${tabKey}`)
    }

    const updateName = (name) => {
        updateQa({
            name: name,
            oldData: {
                name: qaDetail.name
            }
        })
        qaDetail.name = name;
        setQaDetail({ ...qaDetail })
    }

    const updateProjectUser = (userId, user) => {
        updateQa({
            userId: userId,
            payload: {
                userId: user?.nickName
            },
            oldData: {
                name: qaDetail.userId,
                payload: {
                    userId: qaDetail.user?.nickName
                }
            }
        })
        qaDetail.userId = userId;
        qaDetail.user = user;
        setQaDetail({ ...qaDetail })
    }

    const updateStatus = (status) => {
        updateQa({
            status: status,
            oldData: {
                status: qaDetail.status
            }
        })
        qaDetail.status = status;
        setQaDetail({ ...qaDetail })
    }

    const updateActualDate = (actualDate) => {
        if (!checkRangeDateNotNull(actualDate)) {
            message.warning('请输入完成排期！')
            return;
        }
        updateQa({
            actualStartDate: actualDate[0],
            actualEndDate: actualDate[1],
            oldData: {
                actualStartDate: qaDetail.actualStartDate,
                actualEndDate: qaDetail.actualEndDate
            }
        })
        qaDetail.actualStartDate = actualDate[0];
        qaDetail.actualEndDate = actualDate[1];
        setQaDetail({ ...qaDetail })
    }

    const updateProjectDesc = (description) => {
        updateQa({
            description: description,
            oldData: {
                description: qaDetail.description
            }
        })
        qaDetail.description = description;
        setQaDetail({ ...qaDetail })
    }

    const updateProjectProd = (id, item) => {
        updateQa({
            projectProdItemId: id,
            payload: {
                projectProdItemId: item?.name,
            },
            oldData: {
                projectProdItemId: qaDetail.projectProdItemId,
                payload: {
                    projectProdItemId: qaDetail.projectProdItem?.name,
                },
            }
        })
        qaDetail.projectProdItemId = id;
        qaDetail.projectProdItem = item
        setQaDetail({ ...qaDetail })
    }

    const updateProjectDev = (id, item) => {
        updateQa({
            projectDevItemId: id,
            payload: {
                projectDevItemId: item?.name,
            },
            oldData: {
                projectDevItemId: qaDetail.projectDevItemId,
                payload: {
                    projectDevItemId: qaDetail.projectDevItem?.name,
                },
            }
        })
        qaDetail.projectDevItemId = id;
        qaDetail.projectDevItem = item
        setQaDetail({ ...qaDetail })
    }
    const updateQaContent = (content) => {
        const oldDataContent = {
            content: {
                text: qaDetail.content.text
            }
        };
        updateQa({
            content: content,
            oldData: oldDataContent
        })
        qaDetail.content = content;
        setQaDetail({ ...qaDetail })
        setIsDetailTextEditFlag(false)
    }

    const updateModules = (modules) => {
        updateQa({
            modules: modules,
            oldData: {
                modules: qaDetail.modules
            }
        })
        qaDetail.modules = modules;
        setQaDetail({ ...qaDetail })
        setIsModuleEditFlag(false)
    }
    const updateQa = (values) => {
        update(qaDetail.projectId, qaDetail.id, values)
            .then(({ success }) => {
                if (success) {
                    message.success("保存成功")
                }
                setProjectLogUpdate(projectLogUpdate + 1)
            })
    }

    const updatItemIsArchived = (isArchived) => {
        let title = ""
        if (isArchived === 1) {
            title = '确认归档，归档之后无法编辑，只能在归档列表中显示'
        } else {
            title = "确认撤销归档"
        }
        Modal.confirm({
            title: title,
            okText: '确认',
            cancelText: '取消',
            closable: true,
            onOk: (v) => {
                updateIsArchived(projectId, qaId, isArchived)
                    .then(result => {
                        if (result?.success) {
                            message.success("操作成功")
                            setQaDetail({
                                ...qaDetail,
                                isArchived: isArchived
                            })
                        } else {
                            message.success(result?.errMsg)
                        }
                    })
                return Promise.resolve()
            }
        });
    }

    const deleteItem = () => {
        Modal.confirm({
            title: '确认删除，删除之后将无法恢复',
            okText: '确认',
            cancelText: '取消',
            closable: true,
            onOk: (v) => {
                deleteQa(projectId, qaId)
                    .then(result => {
                        if (result?.success) {
                            message.success("操作成功")
                            history.push(`/projects/${projectId}/qa`)
                        } else {
                            message.success(result?.errMsg)
                        }
                    })
                return Promise.resolve()
            }
        });
    }

    const qaDetailRender = (<>
        <Descriptions column={3}>
            <Descriptions.Item label={'模块'} span={3} >  </Descriptions.Item>
            <Descriptions.Item span={3} >
                <EditAble permission={permission}
                    isEdit={isModuleEditFlag}
                    onEdit={() => {
                        setIsModuleEditFlag(true)
                    }}
                    width="100%"
                    useCustomOperate={true}
                    value={(qaDetail.modules && qaDetail.modules.length > 0) ? qaDetail.modules : ""}
                    onCancel={() => {
                        setIsModuleEditFlag(false)
                    }}
                    onSave={() => {
                        setIsModuleEditFlag(false)
                    }}
                    useCustomOperate={true}
                    editComponent={
                        <QaModule.Edit defaultValue={qaDetail.modules}
                            onCancel={() => {
                                setIsModuleEditFlag(false)
                            }}
                            onSave={updateModules}></QaModule.Edit>
                    }>
                    <QaModule modules={qaDetail.modules}></QaModule>
                </EditAble>
            </Descriptions.Item>
            <Descriptions.Item label={'内容'} span={3} >  </Descriptions.Item>
            <Descriptions.Item span={3} >
                <EditAble permission={permission}
                    isEdit={isDetailTextEditFlag}
                    onEdit={() => {
                        setIsDetailTextEditFlag(true)
                    }}
                    width="100%"
                    useCustomOperate={true}
                    value={qaDetail.content && qaDetail.content.raw}
                    onCancel={() => {
                        setIsDetailTextEditFlag(false)
                    }}
                    onSave={() => {
                        setIsDetailTextEditFlag(false)
                    }}
                    useCustomOperate={true}
                    editComponent={
                        <RichTextEdit
                            size="small"
                            onCancel={() => {
                                setIsDetailTextEditFlag(false)
                            }}
                            onSave={updateQaContent}
                            value={qaDetail.content && qaDetail.content.raw}>
                        </RichTextEdit>
                    }>
                    <RichText
                        ellipsis
                        border
                        value={qaDetail.content && qaDetail.content.text}>
                    </RichText>
                </EditAble>
            </Descriptions.Item>
            <Descriptions.Item span={1} />
        </Descriptions>
    </>);

    return <>
        <div className={styles.detailContainer}>
            <PageHeader
                onBack={() => history.go(-1)}
                title={<EditAble permission={permission}
                    value={qaDetail.name}
                    onSave={updateName}
                    type="input">
                    {qaDetail.name}
                </EditAble>}
                extra={[
                    <ActionDropdown
                        key="action"
                        className={styles.actionDropdown}
                        placement="bottomLeft"
                        actions={[
                            qaDetail?.isArchived === 0 ?
                                <TextButton key="archive" type="warning" onClick={() => {
                                    updatItemIsArchived(1)
                                }}>归档</TextButton> :
                                <TextButton key="archive" type="warning" onClick={() => {
                                    updatItemIsArchived(0)
                                }}>撤销归档</TextButton>
                            ,
                            <TextButton key="delete" type="danger" onClick={() => {
                                deleteItem()
                            }}>删除</TextButton>]}
                    />
                ]}
            >
                <Descriptions column={3}>
                    <Descriptions.Item label='负责人' span={1}>
                        <EditAble permission={permission}
                            value={qaDetail.userId}
                            editComponentProps={{
                                projectId: qaDetail.projectId,
                                defaultOpen: true
                            }}
                            onSave={updateProjectUser}
                            type="userSelect">
                            <UserBrief user={qaDetail.user}></UserBrief>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label='状态' span={1}>
                        <EditAble permission={permission}
                            value={qaDetail.status}
                            editComponentProps={{
                                options: ArrayUtils.jsonToArray(PROJECT_QA_STATUS).map(item => {
                                    return { value: item.key, label: item.value.name }
                                }),
                                defaultOpen: true
                            }}
                            onSave={updateStatus}
                            type="select">
                            <QAStatus status={qaDetail.status}></QAStatus>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="创建时间" span={1}>{qaDetail.createTime}</Descriptions.Item>
                    <Descriptions.Item label='所属迭代' span={1}>
                        <EditAble permission={permission}
                            isEdit={isProdEditFlag}
                            onEdit={() => {
                                setIsProdEditFlag(true)
                            }}
                            value={qaDetail?.projectProdItemId === '0' ? null : qaDetail?.projectProdItemId}
                            onCancel={() => {
                                setIsProdEditFlag(false)
                            }}
                            onSave={() => {
                                setIsProdEditFlag(false)
                            }}
                            editComponent={
                                <ProjectProdSelect
                                    onSelect={(projectProdItemId, projectProdItem) => {
                                        setIsProdEditFlag(false)
                                        updateProjectProd(projectProdItemId, projectProdItem)
                                    }}
                                    projectId={projectId}
                                    defaultValue={qaDetail?.projectProdItemId} />
                            }>
                            <TextButton type="text" onClick={() => {
                                if (qaDetail?.projectProdItem) {
                                    history.push(`/projects/${qaDetail.projectId}/prod/${qaDetail?.projectProdItemId}`)
                                }
                            }}>{qaDetail?.projectProdItem?.name}</TextButton>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="关联开发项" span={1}>
                        <EditAble permission={permission}
                            isEdit={isDevEditFlag}
                            onEdit={() => {
                                if (!qaDetail.projectProdItem) {
                                    message.error("请先选择所属迭代");
                                    return;
                                }
                                setIsDevEditFlag(true)
                            }}
                            onCancel={() => {
                                setIsDevEditFlag(false)
                            }}
                            onSave={() => {
                                setIsDevEditFlag(false)
                            }}
                            value={qaDetail?.projectDevItemId === '0' ? null : qaDetail?.projectDevItemId}
                            editComponent={
                                <ProjectDevSelect
                                    params={{
                                        projectProdItemId: qaDetail.projectProdItemId
                                    }}
                                    onSelect={(projectDevItemId, projectDevItem) => {
                                        setIsDevEditFlag(false)
                                        updateProjectDev(projectDevItemId, projectDevItem)
                                    }}
                                    projectId={projectId}
                                    defaultValue={qaDetail?.projectDevItemId} />
                            }>
                            <TextButton type="text" onClick={() => {
                                if (qaDetail?.projectDevItem) {
                                    history.push(`/projects/${qaDetail.projectId}/dev/${qaDetail?.projectDevItemId}`)
                                }
                            }}>{qaDetail?.projectDevItem?.name}</TextButton>
                        </EditAble>
                    </Descriptions.Item>
                    <Descriptions.Item label="排期" span={1}>
                        <EditAble permission={permission}
                            value={[qaDetail.actualStartDate, qaDetail.actualEndDate]}
                            editComponentProps={{
                                format: "YYYY-MM-DD"
                            }}
                            onSave={updateActualDate}
                            type="rangePicker">
                            {`${formetDate(qaDetail.actualStartDate)} - ${formetDate(qaDetail.actualEndDate)}`}
                        </EditAble>
                        {qaDetail.planStartDate && <Tooltip placement="topLeft" title={`预计排期:${formetDate(qaDetail.planStartDate)} - ${formetDate(qaDetail.planEndDate)}`}><ClockCircleOutlined /></Tooltip>}
                    </Descriptions.Item>
                    <Descriptions.Item label="概述" span={3} />
                    <Descriptions.Item span={3} >
                        <EditAble permission={permission}
                            editComponentProps={{
                                rows: 4,
                                maxLength: 200,
                                showCount: true
                            }}
                            width="80%"
                            useCustomOperate={true}
                            editComponentClassName={styles.descriptionTextAreaInput}
                            onSave={updateProjectDesc}
                            value={qaDetail.description}
                            type="textarea">
                            <p>
                                {qaDetail.description}
                            </p>
                        </EditAble>
                    </Descriptions.Item>
                </Descriptions>
                <Tabs
                    activeKey={tabKey}
                    tabBarGutter={-8}
                    tabBarStyle={{ margin: 0 }}
                    onChange={onChangeTabSwitch}
                    className={styles.tabClass}
                >
                    <TabPane tab="内容" key="detail" >
                        {qaDetailRender}
                    </TabPane>
                    <TabPane tab="用例" key="case">
                        <QaCaseList projectId={projectId} qaDetail={qaDetail}></QaCaseList>
                    </TabPane>
                    <TabPane tab="执行" key="casePlan">
                        <QaCasePlanList projectId={projectId} qaDetail={qaDetail} />
                    </TabPane>
                    <TabPane tab="任务" key="task">
                        <TaskPage projectId={projectId} queryInitParams={{
                            projectItemId: qaDetail.id,
                            projectItemType: "QA"
                        }} ></TaskPage>
                    </TabPane>
                    <TabPane tab="甘特图" key="gantt">
                        <TaskGantt projectId={projectId}
                            title={`${qaDetail.name} 的甘特图`}
                            description={qaDetail.description}
                            projectProdId={qaDetail.id}
                            queryInitParams={{
                                projectItemType: "QA",
                                projectItemId: qaDetail.id
                            }}></TaskGantt>
                    </TabPane>
                    <TabPane tab="评论" key="comment">
                        <ProjectComment projectId={projectId} bizId={qaDetail.id} bizType="qa" />
                    </TabPane>
                    <TabPane tab="日志" key="log">
                        <ProjectItemLog
                            projectId={projectId}
                            itemId={qaDetail.id}
                            update={projectLogUpdate}
                            renderField={(value, fieldName, isDetail) => {
                                if (fieldName === "status") {
                                    return <QAStatus status={value}></QAStatus>
                                }
                                if (Array.isArray(fieldName) && fieldName.indexOf("actualStartDate") >= 0) {
                                    return `${formetDate(value["actualStartDate"])} - ${formetDate(value["actualEndDate"])}`
                                }
                                if (fieldName === "modules") {
                                    return <QaModule modules={value}></QaModule>
                                }
                            }}
                            renderFieldName={(fieldName) => {
                                if (fieldName === "projectProdItemId") {
                                    return "所属迭代"
                                }
                                if (fieldName === "projectDevItemId") {
                                    return "所属开发项"
                                }
                                if (fieldName === "modules") {
                                    return "模块"
                                }
                                if (Array.isArray(fieldName) && (fieldName[0] === "actualStartDate" || fieldName[1] === "actualStartDate")) {
                                    return "排期"
                                }
                            }}
                            itemType="qa" />
                    </TabPane>

                </Tabs>
            </PageHeader>
        </div>
    </>
}


export default connect(({ }) => ({
}))(QADetail);